package com.ehome.poct.core.service.pay;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.ehome.exception.RpcException;
import com.ehome.paymentcenter.api.pay.BasePayReqCO;
import com.ehome.paymentcenter.api.pay.domain.PayExtend;
import com.ehome.paymentcenter.api.pay.qrcode.QrCodeReqCO;
import com.ehome.paymentcenter.api.pay.qrcode.QrCodeRspCO;
import com.ehome.poct.core.api.constant.enums.ScanTypeEnums;
import com.ehome.poct.core.api.dto.order.UnificationPayReqDTO;
import com.ehome.poct.core.api.vo.order.PayChannelRespVO;
import com.ehome.web.entity.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * @auther: kuiba.peng
 * @date: 2022/10/28 11:48
 * @description:
 */
@Component("QrCodePayStrategy")
@Slf4j
public class QrCodePayStrategy extends AbstractPayStrategy<QrCodeReqCO, QrCodeRspCO> {

    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
    @Override
    public PayChannelRespVO<QrCodeRspCO> pay(QrCodeReqCO payReqDTO) {
        log.info("qrCode request param:[{}]", JSONUtil.toJsonStr(payReqDTO));
        PayChannelRespVO<QrCodeRspCO> respVO = new PayChannelRespVO<>();
        respVO.setScanType(ScanTypeEnums.C2B);
        String resp;
        try {
            resp = getPayClient().qrCode(payReqDTO);
        } catch (RpcException rpcException) {
            respVO.setBusiCode(rpcException.getBusiCode());
            respVO.setMsg(rpcException.getMsg());
            return respVO;
        } catch (Exception e) {
            respVO.setBusiCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return respVO;
        }

        log.info("qrCode response body:[{}]", resp);
        ResponseWrapper<QrCodeRspCO> responseWrapper = JSONUtil.toBean(resp, new TypeReference<ResponseWrapper<QrCodeRspCO>>() {
        }, false);
        respVO.setData(responseWrapper.getData());
        respVO.setBusiCode(responseWrapper.getBusiCode());
        respVO.setMsg(responseWrapper.getMsg());
        return respVO;

    }

    @Override
    public PayChannelRespVO<QrCodeRspCO> pay(UnificationPayReqDTO payReqDTO) {
        BasePayReqCO basePayReqCO = unificationPayMapping.toBasePayReq(payReqDTO);
        QrCodeReqCO qrCodeReqCO = BeanUtil.copyProperties(basePayReqCO,QrCodeReqCO.class);
        qrCodeReqCO.setTimeoutExpress(payReqDTO.getTimeoutExpress());

        PayExtend payExtend = getPayExtend(payReqDTO.getOrderItemList(), payReqDTO.getProfitsRecordList(), payReqDTO.getPayMoney());
        qrCodeReqCO.setPayExtend(payExtend);
        log.info("qrCode request payExtend:[{}]", JSONUtil.toJsonStr(payExtend));

        return pay(qrCodeReqCO);
    }

    @Override
    public ScanTypeEnums getSupportType() {
        return ScanTypeEnums.C2B;
    }

    @Override
    public boolean supports(Object payReqDTO) {
        return payReqDTO instanceof QrCodeReqCO;
    }
}
